package com.example.myandroidtest.common.http;


import com.example.myandroidtest.utils.PrintUtils;
import com.example.myandroidtest.utils.ToastUtils;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ReqeustPrintInterceptor implements Interceptor {

    public final String GET = "GET";
    public final String POST = "POST";

    private static boolean isParamsDebug = true;// 是否输出请求参数

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request(); //获取
        Map<String, String> paramMap = getParameterMap(request); // 获取参数
        printParamsLog(request, paramMap);// log打印网络请求参数
        Request signRequest = request.newBuilder().build();
        return chain.proceed(signRequest);
    }


    /**
     * 获取 get  post 请求参数 然后装进map
     *
     * @param request
     * @return
     */
    public Map<String, String> getParameterMap(Request request) {
        String method = request.method(); //获取请求类型
        if (method.equals(GET)) { // get请求
            return getGetReuqestParameter(request);
        } else if (method.equals(POST)) { // post请求
            return getPostRequestBody(request);
        }
        return new HashMap<>();
    }


    /**
     * 得到get请求参数
     *
     * @param request
     * @return
     */
    public Map<String, String> getGetReuqestParameter(Request request) {
        Map<String, String> parameterMap = new HashMap<>();
        HttpUrl url = request.url();
        for (int i = 0; i < url.querySize(); i++) {
            String encodedName = url.queryParameterName(i);
//            if (interceptPrint(encodedName)) {
//                continue;
//            }
            String encodedValue = url.queryParameterValue(i);
            parameterMap.put(encodedName, encodedValue);
        }
        return parameterMap;
    }


    /**
     * 得到 post  body
     *
     * @param request
     * @return
     */
    public Map<String, String> getPostRequestBody(Request request) {
        Map<String, String> parameterMap = new HashMap<>();
        RequestBody body = request.body();
        if (body != null && body instanceof FormBody) {
            FormBody formBody = (FormBody) body;
            for (int i = 0; i < formBody.size(); i++) {
                String encodedName = formBody.encodedName(i);
                String encodedValue = HttpUrlUtils.decode(formBody.encodedValue(i));
                parameterMap.put(encodedName, encodedValue);
            }
        }
        return parameterMap;
    }


    public Map<String, String> getPostMultipartBody(Request request) {
        Map<String, String> parameterMap = new HashMap<>();
        RequestBody body = request.body();
        if (body != null && body instanceof MultipartBody) {
            MultipartBody formBody = (MultipartBody) body;
            List<MultipartBody.Part> parts = formBody.parts();
            for (MultipartBody.Part part : parts) {
                Set<String> names = part.headers().names();
                for (String name : names) {
                    String key = name;
                    String content = part.headers().get("form-data");
                    ToastUtils.showLong("key  " + key + "  content  " + content);
                }
            }
        }
        return null;
    }


    /**
     * @param name
     */
    public boolean interceptPrint(String name) {
        return true;
    }


    /**
     * log打印网络请求参数
     *
     * @param request
     * @param paramMap
     */
    private void printParamsLog(Request request, Map<String, String> paramMap) {
        if (isParamsDebug) {
            // get url  http://192.168.1.240:8010/api/Members/GetMemberInfo?
            // mid=144118079817908224&timestamp=20180413135119
            // post url  http://192.168.1.240:8010/api/Members/GetMemberInfo

            //请求接口  append
            StringBuilder urlSb = new StringBuilder();

            urlSb.append("-----\t");
            List<String> pathSegments = request.url().pathSegments();
            int size = pathSegments.size();
            for (int i = 0; i < pathSegments.size(); i++) {
                String pathSegment = pathSegments.get(i);
                if (i == (size - 1)) {
                    urlSb.append(pathSegment);
                } else {
                    urlSb.append(pathSegment).append("/");
                }
            }
            urlSb.append("\t-----\n");


            // 装进去 url
            StringBuilder sbLog = new StringBuilder(urlSb);
//            sbLog.append("------params-----\n");
            String[] keyArray = paramMap.keySet().toArray(new String[0]);
            Arrays.sort(keyArray, String.CASE_INSENSITIVE_ORDER);

            for (String name : keyArray) {
                sbLog.append(name).append(" : ").append(paramMap.get(name)).append("\n");
            }
            PrintUtils.printMoreContent("print", sbLog.toString());
        }
    }
}
